<?php
namespace backend\controllers;

use common\components\BaseController;
use Yii;
use yii\db\Query;
use \common\helps\tools;
use \common\helps\code;

/**
 * User controller
 */
class LoginController extends BaseController
{

    public $modelClass = 'backend\models\Admin';
    public function init()
    {
        $this->enableAuth=false;
        parent::init();
    }

    public function actionLogin()
    {
        $admin = new \backend\models\Admin();
        $session = Yii::$app->session;
        //$redis = Yii::$app->cache;
        $request =$this->request;
        $params = $request->bodyParams;

        $code = $session->get('code');
        if(empty($params['code'])){
            return code::error('codeEmpty');
        }
        if(!empty($code['expire_time']) && $code['expire_time'] < time()){
            return code::error('codeTime');
        }
        if($code['title'] != $params['code']){
            return code::error('codeFail');
        }
        $info = $admin::findDataByUsername($params['username']);
        if(empty($info)){
            return code::error('','用户名不存在');
        }
        $info = $info->toArray();
        if($info['password'] == sha1(md5($params['password'].$info['salt']))){
            $transaction = Yii::$app->db->beginTransaction();
            try {
                $session->set('username',$info['username']);
                $session->set('user_id',$info['id']);
                $data = [
                    'id' => $info['id'],
                    'expire_time' => time() + 3600,
                ];
                $session['admin_id'] = $data;
                $data['token'] = tools::generateRandomString(16);
                $admin->saveUserInfo('update',$data,$info['id']);
                $transaction->commit();
                return code::success(['token' => $data['token'],'username' => $info['username'],'id' => $info['id']],'登录成功');
            } catch (\Exception $e) {
                $transaction->rollBack();
                throw $e;
            }
        }else{
            return code::error('pwdError');
        }
    }

    public function actionGetPicCode()
    {
        $imageCode = tools::verifyCode();
        return code::success($imageCode);
    }

    public function actionLogout(){
        $session = Yii::$app->session;
        $session->remove('user_id');
        return code::success();
    }

}
